package com.vital.mshopping;

import java.util.ArrayList;

import com.vital.dao.Category;
import com.vital.service.DatabaseService;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

public class AddCategoryActivity extends Activity {
	Button btnSave;
	Button btnBack;
	EditText txtCateName;
	ImageView imgChooseIcon;
	int request_Code = 1;
	
	int cateId = -1; 
	String cateName = "";
	String cateIcon = "atm";
	
	ArrayList<Category> categories;
	Category editedCategory;
	boolean isEdit = false;
	
	Category updatedCategory;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_category);
		
		txtCateName = (EditText)findViewById(R.id.txtCategoryName);
		btnSave = (Button)findViewById(R.id.btnSave);
		btnBack = (Button)findViewById(R.id.btnBack);
		imgChooseIcon = (ImageView)findViewById(R.id.imgChooseIcon);
		
		btnSave.setOnClickListener(btnSave_click);
		btnBack.setOnClickListener(btnBack_click);
		imgChooseIcon.setOnClickListener(imgChooseIcon_click);
		
		categories = new ArrayList<Category>();
		
		isEdit = false;
		Intent intent = this.getIntent();
		Bundle b = intent.getExtras();
		if (b != null) {
			if (b.getSerializable("editCategoryObject") != null) {
				Category category = (Category)b.getSerializable("editCategoryObject");
				
				cateId = category.getCateId();
				cateName = category.getCateName();
				cateIcon = category.getCateIcon();
				
				updatedCategory = new Category();
				updatedCategory.setCateId(cateId);
				updatedCategory.setCateName(cateName);
				updatedCategory.setCateIcon(cateIcon);
				updatedCategory.setCateReadOnly(0);
				
				imgChooseIcon.setImageResource(this.getResources().getIdentifier(cateIcon,
						"drawable", this.getPackageName()));
				txtCateName.setText(cateName);
				btnSave.setText("Update");
				isEdit = true;
			} 
		}
				
//		if (intent != null) {
//			editedCategory = (Category) intent.getSerializableExtra("editCategoryObject");
//			if (editedCategory != null) {
//				cateId = editedCategory.getCateId();
//				cateName = editedCategory.getCateName();
//				cateIcon = editedCategory.getCateIcon();
//				imgChooseIcon.setImageResource(this.getResources().getIdentifier(cateIcon,
//													"drawable", this.getPackageName()));
//				txtCateName.setText(cateName);
//				btnSave.setText("Update");
//				
//				updatedCategory = new Category(cateId, cateName, cateIcon, 0);
//				isEdit = true;
//			} else {
//				isEdit = false;
//			}
//		}
//		
	}
	
	private OnClickListener btnSave_click = new OnClickListener() {
		
		public void onClick(View v) {
			// TODO Auto-generated method stub
			cateName = txtCateName.getText().toString();
			Category category = new Category(cateId, cateName, cateIcon, 0);
			
			DatabaseService db = new DatabaseService(getApplicationContext());
			if (isEdit) {
				onUpdateCategory(db, category);
			} else {
				onInsertCategory(db, category);
			}
		}
	}; 
	
	private void onUpdateCategory(DatabaseService db, Category category) {
		db.open();
		if (db.updateCategory(category)) {
			db.close();
			updatedCategory = category;
			finish();
		}
		
	}
	
	private void onInsertCategory(DatabaseService db, Category category) {
		db.open();
		long cateId = db.insertCategory(category);
		if (cateId != -1) {
			clean();
			showMessage("Successful", "Category has been added successfully!");
			Category item = new Category((int)cateId, cateName, cateIcon, 0);
			categories.add(item);
		} else {
			showMessage("Error", "Category does not add! Please try again.");
		}
		db.close();
	}
	
	/**
	 * Event click button Back
	 */
	private OnClickListener btnBack_click = new OnClickListener() {
		
		public void onClick(View v) {
			// TODO Auto-generated method stub
			finish();
		}
	};
	
	/**
	 * Event click image category
	 */
	private OnClickListener imgChooseIcon_click = new OnClickListener() {
		
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(getApplicationContext(), ImageViewActivity.class);
			startActivityForResult(intent, request_Code);
		}
	};
	
	/**
	 * The returned Data from Image View Activity
	 */
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == request_Code) {
			if (resultCode == RESULT_OK) {
				int position = data.getIntExtra("posImage", 0);
				ImageAdapter imageAdapter = new ImageAdapter(this);
				imgChooseIcon.setImageResource(imageAdapter.mDrawableIds[position]);
				String resName = imageAdapter.mDrawables[position].toString();
				String[] convertName = resName.split("/");
				String tmpCateIcon = convertName[convertName.length - 1];
				cateIcon = tmpCateIcon.substring(0, tmpCateIcon.length() - 4);
			}
		}
	}
	
	/**
	 * Clean text box
	 */
	private void clean() {
		txtCateName.setText("");
		imgChooseIcon.setImageResource(R.drawable.atm);
	}
	
	/**
	 * Dialog message
	 */
	private void showMessage(String title, String msg) {
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle(title);
		dialog.setMessage(msg);
		dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				//---Hide dialog---
				dialog.dismiss();
			}
		});
		dialog.show();
	}
	
	
	private void onBack() {
		
		Intent intent = new Intent();
		if (isEdit) {
			intent.putExtra("updatedCategory", updatedCategory);
			setResult(RESULT_OK, intent);
		} else {
			intent.putExtra("list_added_categories", categories);
			setResult(RESULT_OK, intent);
		}
		
		Log.i("mShopping", "back view");
		
		//---Set the data to pass back---
		
	}

	
	@Override
	public void finish() {
		// TODO Auto-generated method stub
		onBack();
		super.finish();
	}
}
